﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Account_Logon : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        MasterPage master = (MasterPage)this.Master;
        Menu navMenu = (Menu)master.FindControl("NavigationMenu");
        navMenu.Visible = false;
        RegisterHyperLink.NavigateUrl = "~/Account/Register.aspx";
        if (Session["loginEr"] != null)
        {
            ErrorLabel.Text = "incorrect login or password";
        }
    }

    /// <summary>
    /// Add cookies to responce.
    /// </summary>
    /// <param name="login"></param>
    /// <param name="createPersCookie"></param>
    private void AddCookies(string user_id, bool createPersCookie)
    {
        HttpCookie authCookie = FormsAuthentication.GetAuthCookie(user_id, createPersCookie);
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
        FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, LoginUser.UserName);
        authCookie.Value = FormsAuthentication.Encrypt(newTicket);
        Response.Cookies.Add(authCookie);
    }

    /// <summary>
    /// Authenticate user.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LoginButton_Click(object sender, EventArgs e)
    {
        string login = LoginUser.UserName;
        string pass = LoginUser.Password;
        MatrixData sd = new MatrixData();
        int user_id = sd.getUserIdFromLoginAndPassword(login, pass);
        if (user_id != -1)
        {
            LoginUser.UserName = user_id+"";
            AddCookies(LoginUser.UserName, LoginUser.RememberMeSet);
            string redirUrl = FormsAuthentication.GetRedirectUrl(LoginUser.UserName, true);
            Session["loginEr"] = null;
            if (redirUrl.Equals("/default.aspx"))
                Response.Redirect("~/ViewProfile.aspx");
            Response.Redirect(redirUrl);
        }
        else
        {
            Session["loginEr"] = "login or password are incorrect";
            Response.Redirect("~/Account/login.aspx");
        }
    }
    protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
    {

    }
}